﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;

namespace Demo.Gateway;

public static class JwtTokenMiddleware
{
    public static IApplicationBuilder UseJwtTokenMiddleware(this IApplicationBuilder app, string schema = JwtBearerDefaults.AuthenticationScheme)
    {
        return app.Use(async (ctx, next) =>
        {
            //如果上游服务客户端传入UserID则先清空
            if (ctx.Request.Headers.ContainsKey("UserId"))
            {
                ctx.Request.Headers.Remove("UserId");
            }

            if (ctx.User.Identity?.IsAuthenticated != true)
            {
                var result = await ctx.AuthenticateAsync(schema);
                //如果如果可以获取到用户信息则将用户ID写入Header
                if (result.Succeeded && result.Principal != null)
                { 
                        
                    ctx.User = result.Principal;
                    var uid = result.Principal.Claims.First(x => x.Type == "sub").Value;
                    ctx.Request.Headers.Add("UserId",uid);
                }
            }

            await next();
        });
    }
}